﻿using System;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;
using CIK.News.Framework;
using CIK.News.Framework.Extensions;
using CIK.News.Web.Infrastructure.Repository;
using CIK.News.Web.Infrastructure.ViewModels.Admin.DashBoard;

namespace CIK.News.Web.Infrastructure.ActionResults.Admin
{
    public class ItemEditingViewModelActionResult<TController> : ActionResultBase<TController> where TController : Controller
    {
         #region variables & ctors

        private readonly ICategoryRepository _categoryRepository;
        private readonly IItemRepository _itemRepository;

        private readonly int _itemId;

        public ItemEditingViewModelActionResult(
                Expression<Func<TController, ActionResult>> viewNameExpression,
                int itemId)
            : this(viewNameExpression, itemId,
                   DependencyResolver.Current.GetService<ICategoryRepository>(),
                   DependencyResolver.Current.GetService<IItemRepository>())
        {
        }

        public ItemEditingViewModelActionResult(
            Expression<Func<TController, ActionResult>> viewNameExpression,
            int itemId,
            ICategoryRepository categoryRepository,
            IItemRepository itemRepository)
            : base(viewNameExpression)
        {
            _categoryRepository = categoryRepository;
            _itemRepository = itemRepository;
            _itemId = itemId;
        }

        #endregion

        #region implementation

        public override void ExecuteResult(ControllerContext context)
        {
            base.ExecuteResult(context);

            var item = _itemRepository.GetById(_itemId);

            if (item == null)
                throw new NoNullAllowedException(string.Format("Item with id={0}", _itemId).ToNotNullErrorMessage());

            var viewModel = item.MapTo<ItemEditingViewModel>();

            viewModel.Categories = _categoryRepository.GetCategories().ToList();

            GetViewResult(viewModel).ExecuteResult(context);
        }

        public override void EnsureAllInjectInstanceNotNull()
        {
            Guard.ArgumentNotNull(_categoryRepository, "CategoryRepository");
            Guard.ArgumentNotNull(_itemRepository, "ItemRepository");
            Guard.ArgumentMustMoreThanZero(_itemId, "ItemId");
        }

        #endregion
    }
}